package com.wzh.core.api.balance;

import com.wzh.core.api.LoadBalance;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: 轮询负载均衡
 * @author: wangzouhuax
 */
public class RoundLoadBalance<T> implements LoadBalance<T> {

    private static AtomicInteger count = new AtomicInteger(0);
    @Override
    public T choose(List<T> urls) {
        if (CollectionUtils.isEmpty(urls)) {
            return null;
        }
        if (urls.size() == 1) {
            return urls.get(0);
        }
//        return urls.get(count.getAndIncrement()%urls.size());
        // & 0x7fffffff：将获取的值与0x7fffffff进行位与操作，确保结果为非负数
        return urls.get((count.getAndIncrement() & 0x7fffffff) %urls.size());
    }
}
